#include <head.h>
union semun{
    int val;
    struct semid_ds *buf;
};

int semnum_init_value(int semid, int which, int value){
    union  semun sem={
        .val = value,
    };
    if(semctl(semid,which,SETVAL,sem) == -1)
        PRINT_ERR("semclt int value error");

    return 0;
}
//初始化信号灯集
int my_sem_init(int nsems){
    key_t key;
    int semid;
    //1.通过ftok获取键值
    if((key = ftok("/home/linux/",'s')) == -1)
        PRINT_ERR("get key error");
    //2.创建信号灯集 
    if((semid =semget(key,nsems,IPC_CREAT |IPC_EXCL|0666)) == -1){
        if(errno == EEXIST){
            semid = semget(key,nsems,IPC_CREAT|0666);
        }else{
            PRINT_ERR("crate sem error");
        }
    }else{
        //初始化信号灯
        int i =0;
        for(i =0;i<nsems;i++){
            semnum_init_value(semid,i, !i);  
        }
    }
    return nsems;
}
//申请资源
int P(int semid,int semunm){
    struct sembuf buf = {
        .sem_num=semunm,
        .sem_op = -1,
        .sem_flg = 0,
    };
    if(semop(semid,&buf,1))
        PRINT_ERR("request resource error");
    
    return 0;
}
//释放资源
int V(int semid,int semunm){
    struct sembuf buf = {
        .sem_num=semunm,
        .sem_op = 1,
        .sem_flg = 0,
    };
    if(semop(semid,&buf,1))
        PRINT_ERR("free resource error");    

    return 0;
}

int sem_del(int semid){
    semctl(semid,0,IPC_RMID);
}